package com.hangxiang.approval.controller;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hangxiang.approval.common.ResultBean;
import com.hangxiang.approval.dao.UserDao;
import com.hangxiang.approval.entity.User;
import com.hangxiang.approval.enums.ResultStatusEnum;
import com.hangxiang.approval.exception.MyException;
import com.hangxiang.approval.utils.HttpUtil;
import com.hangxiang.approval.vo.UserVo;
import com.hangxiang.approval.wx.WXBizDataCrypt;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("wx")
public class MiniProgramLogin {

    // 小程序 AppID
    private static final String appid = "wx562803d8b66dfafb";
    // 小程序 AppSecret
    private static final String secret = "0f9e25bb53e8b2b23e928ca1fd486e1d";

    @Resource
    private UserDao userDao;

    /**
     * 小程序授权登录
     */
    @RequestMapping(value = "/miniLogin")
    @ResponseBody
    public Map<String, Object> miniLogin(String code, String encryptedData, String iv) {
        Map<String, Object> map = new HashMap<>();

        String params = "appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
        String s = HttpUtil.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
        JSONObject jsonObject = JSONObject.parseObject(s);

        String session_key = jsonObject.getString("session_key");
        String openid = jsonObject.getString("openid");
        String unionid = jsonObject.getString("unionid");

        String result = WXBizDataCrypt.decrypt1(encryptedData, session_key, iv);
        JSONObject json = JSONObject.parseObject(result);

        if (!StringUtils.isEmpty(result) && result.length() > 0) {
            String sex = "";
            if (json.getInteger("gender") == 1) {
                sex = "男";
            } else if (json.getInteger("gender") == 2) {
                sex = "女";
            }
            if (unionid != null) {
                map.put("unionid", unionid);
            } else {
                map.put("unionid", null);
            }
            map.put("session_key", session_key);
            map.put("openid", openid);
            map.put("avatarUrl", json.getString("avatarUrl"));
            map.put("nickName", json.getString("nickName"));
            map.put("sex", sex);
            map.put("msg", "success");
            return map;
        }
        map.put("msg", "error");
        return map;
    }


    /**
     * 小程序授权获取手机号
     */
    @RequestMapping(value = "/getPhoneNumber")
    @ResponseBody
    public UserVo getPhoneNumber(String encryptedData, String iv, String session_key) {
        String result = WXBizDataCrypt.decrypt1(encryptedData, session_key, iv);
        JSONObject json = JSONObject.parseObject(result);
        UserVo vo = new UserVo();
        if (!StringUtils.isEmpty(result) && result.length() > 0) {
            // 手机号进行匹配，获取
            User purePhoneNumber = userDao.selectOne(new QueryWrapper<User>().lambda().eq(User::getPhone, json.getString("purePhoneNumber")));
            if (purePhoneNumber == null) {
                throw  new MyException(ResultStatusEnum.USER_DATA);
            }
            if (purePhoneNumber.getIsForbidden().equals(1)){
                throw  new MyException(ResultStatusEnum.FORBIDDEN);
            }
            BeanUtils.copyProperties(purePhoneNumber,vo);
            return vo;
        }
        throw  new MyException(ResultStatusEnum.DATA_ERR);
    }


}